package com.jinbaoty.recyclebins.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.hardware.camera2.CameraManager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.camerakit.CameraKitView;
import com.jinbaoty.recyclebins.R;
import com.jinbaoty.recyclebins.utils.DataHelper;
import com.jinbaoty.recyclebins.utils.camera.CameraHelper;
import com.jinbaoty.recyclebins.utils.camera.CameraListener;
import com.orhanobut.logger.Logger;

import java.io.ByteArrayOutputStream;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CameraActivity extends AppCompatActivity implements ViewTreeObserver.OnGlobalLayoutListener{

    private final String TAG = "cameraActivity";

//    private CameraKitView cameraKitView;

    private CameraHelper cameraHelper;

    /**
     * 相机预览显示的控件，可为SurfaceView或TextureView
     */
    private View previewView;

    private Integer rgbCameraID = 1;

    private int takePhotoBtnState = 0;

    private TextView timerTextView ;

    @Override
    protected void onDestroy() {
        if (cameraHelper != null) {
            cameraHelper.release();
            cameraHelper = null;
        }
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        //cameraKitView = findViewById(R.id.camera);
        Intent intent = getIntent();
        timerTextView = findViewById(R.id.faceCheckTimer);
        previewView = findViewById(R.id.single_camera_texture_preview);
        //在布局结束后才做初始化操作
        previewView.setScaleX(-1);
        previewView.getViewTreeObserver().addOnGlobalLayoutListener(this);

        int cameraType = intent.getIntExtra("cameraType", 1);
        rgbCameraID = cameraType;
        /*//cameraKitView.setFacing(cameraType);
        //cameraKitView.setCameraListener(new CameraKitView.CameraListener() {
            @Override
            public void onOpened() {
                Logger.d("相机打开");
            }

            @Override
            public void onClosed() {
                Logger.d("相机关闭");
            }
        });*/

        //initCamera(cameraType);
        startTimer();
    }

    @Override
    protected void onStart() {
        super.onStart();
        //cameraKitView.onStart();
        Logger.d("相机权限返回");


    }

    @Override
    protected void onResume() {
        super.onResume();
        //cameraKitView.onResume();

    }

    @Override
    protected void onPause() {
        //cameraKitView.onPause();
        super.onPause();
    }

    @Override
    protected void onStop() {
        //cameraKitView.onStop();
        super.onStop();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        Logger.d("权限结果："+permissions);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //cameraKitView.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }
    public void takePhoto(View view){
        /*//cameraKitView.captureImage(new CameraKitView.ImageCallback() {
            @Override
            public void onImage(CameraKitView //cameraKitView, byte[] bytes) {
                Intent intent = getIntent();
                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                DataHelper.getInstance().saveData("photoData",bitmap);
                setResult(RESULT_OK,intent);
                finish();

            }
        });*/
        //Camera camera = cameraHelper.getmCamera();
        takePhotoBtnState =1;
    }
    public void backIndex(View view){
            setResult(RESULT_CANCELED);
            this.finish();
    }

    private Bitmap cameraTakePhoto(Camera camera,byte[] data){
        Camera.Size previewSize = camera.getParameters().getPreviewSize();//获取尺寸,格式转换的时候要用到
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        YuvImage yuvimage = new YuvImage(
                data,
                ImageFormat.NV21,
                previewSize.width,
                previewSize.height,
                null);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        yuvimage.compressToJpeg(new Rect(0, 0, previewSize.width, previewSize.height), 100, baos);// 80--JPG图片的质量[0-100],100最高
        byte[] imageByte = baos.toByteArray();
        //将imageByte转换成bitmap
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = BitmapFactory.decodeByteArray(imageByte, 0, imageByte.length, options);
        return bitmap;
    }



    private void initCamera(Integer rgbCameraID) {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        CameraListener cameraListener = new CameraListener() {
            @Override
            public void onCameraOpened(Camera camera, int cameraId, int displayOrientation, boolean isMirror) {

            }


            @Override
            public void onPreview(final byte[] nv21, Camera camera) {
                if(takePhotoBtnState==1) {
                    takePhotoBtnState = 0;
                    Bitmap bitmap = cameraTakePhoto(camera, nv21);
                    Intent intent = getIntent();
                    DataHelper.getInstance().saveData("photoData", bitmap);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }

            @Override
            public void onCameraClosed() {
                Log.i(TAG, "onCameraClosed: ");
            }

            @Override
            public void onCameraError(Exception e) {
                Log.i(TAG, "onCameraError: " + e.getMessage());
            }

            @Override
            public void onCameraConfigurationChanged(int cameraID, int displayOrientation) {

                Log.i(TAG, "onCameraConfigurationChanged: " + cameraID + "  " + displayOrientation);
            }
        };

        int cameraId = rgbCameraID != null ? rgbCameraID : Camera.CameraInfo.CAMERA_FACING_FRONT;
        //showToast("cameraId:"+cameraId+",front:"+Camera.CameraInfo.CAMERA_FACING_FRONT+",back:"+Camera.CameraInfo.CAMERA_FACING_BACK);
        cameraHelper = new CameraHelper.Builder()
                .previewViewSize(new Point(previewView.getMeasuredWidth(), previewView.getMeasuredHeight()))
                .rotation(getWindowManager().getDefaultDisplay().getRotation())
                .specificCameraId(cameraId)
                .isMirror(false)
                .previewOn(previewView)
                .cameraListener(cameraListener)
                .build();
        cameraHelper.init();
        cameraHelper.start();
    }

    private static final int ACTION_REQUEST_PERMISSIONS = 0x001;
    /**
     * 所需的所有权限信息
     */
    private static final String[] NEEDED_PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE

    };
    @Override
    public void onGlobalLayout() {

        previewView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        boolean checkPermissions = checkPermissions(NEEDED_PERMISSIONS);
        Logger.d("检查权限："+checkPermissions);
        if (!checkPermissions) {
            ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, ACTION_REQUEST_PERMISSIONS);
        } else {
            initCamera(rgbCameraID);
        }
    }
    /**
     * 权限检查
     *
     * @param neededPermissions 需要的权限
     * @return 是否全部被允许
     */
    protected boolean checkPermissions(String[] neededPermissions) {
        if (neededPermissions == null || neededPermissions.length == 0) {
            return true;
        }
        boolean allGranted = true;
        for (String neededPermission : neededPermissions) {
            allGranted &= ContextCompat.checkSelfPermission(this, neededPermission) == PackageManager.PERMISSION_GRANTED;
        }
        return allGranted;
    }

    private Timer backIndexTimer;


    private int getIntFromStr(String text){
        Pattern p = Pattern.compile("(\\d+)");
        Matcher m = p.matcher(text);
        String numStr = "";
        if(m.find()){
            numStr = m.group(1);
            return Integer.parseInt(numStr);
        }else{
            return -1;
        }


    }
    public void startTimer(){
        if(backIndexTimer==null){
            backIndexTimer = new Timer();
            backIndexTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(
                            new Runnable() {
                                @Override
                                public void run() {
                                    String timeStr = timerTextView.getText().toString();

                                    int time = getIntFromStr(timeStr);
                                    time--;
                                    if(time<=0){
                                        backIndexTimer.cancel();
                                        backIndexTimer = null;
                                        setResult(RESULT_CANCELED);
                                        finish();
                                    }else{
                                        timerTextView.setText(timeStr.replaceFirst("\\d+",time+""));
                                    }
                                }
                            }
                    );

                }
            },0,1000);
        }
    }
}
